package com.jlpay.open.jlpay.sdk.java.utils.gm.keyentity;

import com.jlpay.open.jlpay.sdk.java.utils.gm.Sm4Utils;

import java.util.Base64;

/**
 * SM4密钥实体
 *
 * @author zhangyinda
 * @since 2023/8/3
 */
public class Sm4KeyEntity {
    /**
     * 密钥
     */
    private byte[] key;

    public void initKey(String key) {
        this.key = Base64.getDecoder().decode(key);
    }

    public String encrypt(String plaintext) {
        try {
            byte[] encryptResult = Sm4Utils.encryptEcbPadding(key, plaintext.getBytes());
            return new String(Base64.getEncoder().encode(encryptResult));
        } catch (Exception e) {
            throw new RuntimeException("Sm4 encrypt fail: " + e);
        }
    }

    public String decrypt(String ciphertext) {
        try {
            byte[] valueEncrypted = Base64.getDecoder().decode(ciphertext);
            byte[] result = Sm4Utils.decryptEcbPadding(key, valueEncrypted);
            return new String(result);
        } catch (Exception e) {
            throw new RuntimeException("Sm4 decrypt fail: " + e);
        }
    }
}
